package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IAppointmentService;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private IAppointmentService appointmentService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public void save(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {

        bpmnInfoMapper.updateInfo(bpmnInfo);

    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }


    @Override
    public String bpmnUpload(MultipartFile file) {
        //思考: 将上传文件保存在哪个位置??
        //springboot项目最终运行打包jar的, 如果将upload文件添加到jar中, 后续文件上传会出问题
        //将upload 文件夹 放置其他位置(只要不是在项目目录都可以)
        String path = null;
        if(file != null && file.getSize() > 0){
            //合法: 后缀名  .zip   .bpmn
            //获取上传文件的后缀名  c:/xxx/xxx.jpg--->jpg
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if("ZIP".equals(ext.toUpperCase()) || "BPMN".equals(ext.toUpperCase())){
                //文件上传逻辑
                try {
                    path =  FileUploadUtils.upload(SystemConfig.getUploadPath(), file);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new BusinessException("文件上传出错, 请按要求上传文件");
                }
            }else{
                throw new BusinessException("只能上传后缀名为zip或者bpmn文件");
            }
        }else{
            throw new BusinessException("请上传合法的流程文件");
        }

        return path;
    }

    @Override
    public void deploy(BpmnInfo bpmnInfo) throws Exception {
        //部署流程
        String ext = FilenameUtils.getExtension(bpmnInfo.getBpmnPath());
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());
        DeploymentBuilder builder = repositoryService.createDeployment();
        if("zip".equals(ext.toLowerCase())){
            //zip
            builder.addZipInputStream(new ZipInputStream(new FileInputStream(file)));
        }else if("bpmn".equals(ext.toLowerCase())){
            //bpmn
            //使用路径做为资源名称
            builder.addInputStream(bpmnInfo.getBpmnPath(), new FileInputStream(file));
        }else{
            throw new BusinessException("流程文件部署失败");
        }
        //部署
        Deployment deployment = builder.deploy();
        //保存-BpmnInfo
        //获取部署成功的流程定义对象:ProcessDefinition
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();
        bpmnInfo.setDeploymentId(deployment.getId());  //流程部署的id
        bpmnInfo.setActProcessId(processDefinition.getId());    //流程定义的id
        bpmnInfo.setActProcessKey(processDefinition.getKey());   //流程定义的key
        bpmnInfo.setBpmnName(processDefinition.getName());       //流程定义名称
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());  //部署时间
        bpmnInfoMapper.insert(bpmnInfo);

    }

    @Override
    public void delete(Long id) {
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        //1:删除流程文件
        File file = new File(SystemConfig.getProfile(), bpmnInfo.getBpmnPath());
        if(file.exists()){
            file.delete();
        }
        //3:级联删除该流程下启动所有实例 @TODO
        List<ProcessInstance> instances = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(bpmnInfo.getActProcessKey())
                .list();

        for (ProcessInstance instance : instances) {
            ///获取businesskey---通过key获取serviceItem对象--养修服务套餐对象
            //2:恢复审核数据状态  -- @TODO
        }
        //删除
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);

        //4:删除部署流程定义对象
        bpmnInfoMapper.deleteByPrimaryKey(id);

    }

    @Override
    public InputStream readResource(String deploymentId, String type) {

        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId)
                .latestVersion().singleResult();
        InputStream inputStream = null;
        if("xml".equals(type)){
            //文件
            inputStream = repositoryService.getResourceAsStream(deploymentId, definition.getResourceName());
        }else if("png".equals(type)){
            //图片
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");

        }

        return inputStream;
    }

    @Override
    public BpmnInfo queryByType(String type) {
        return bpmnInfoMapper.selectByType(type);
    }
}
